<template>
<div class="container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
        <el-row :gutter="10">
            <el-col :span="8">
                <el-input placeholder="请输入内容" v-model="queryinfo.query" clearable @clear="getUsers" >
                    <el-button slot="append"  @click="getUsers" icon="el-icon-search"></el-button>
                </el-input>
            </el-col>
            <el-col :span=4><el-button type="primary" @click="showAddDialog()">添加</el-button></el-col>
        </el-row>
        <!-- 用户数据 -->
       <el-table :data="userlist" border >
            <el-table-column type="index" label="序号" width="50"> </el-table-column>
            <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
            <el-table-column prop="mobile" label="电话" width="180"> </el-table-column>
            <el-table-column prop="role_name" label="角色" width="180"> </el-table-column>
            <el-table-column prop="mg_state" label="状态" width="180">
                <template slot-scope="scope">
                    <el-switch @change="changeState(scope.row)" v-model="scope.row.mg_state"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" @click="showeditDialog(scope.row)" size="small" icon="el-icon-edit"></el-button>
                    <el-button type="danger"  @click="deleteUser(scope.row.id)" size="small" icon="el-icon-delete"></el-button>
                    <el-tooltip content="分配角色" placement="top">
                        <el-button type="primary" @click="setUser(scope.row)" size="small" icon="el-icon-setting"></el-button>       
                    </el-tooltip>
                </template>
            </el-table-column>
       </el-table>

       <!-- 分页 -->
       <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryinfo.pagenum"
      :page-sizes="[3, 5, 10, 20]" :page-size="queryinfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination> 
    </el-card>

    <!-- 添加dialog对话框 -->
    <el-dialog title="添加用户信息" @close="hiddenAddDialog" :visible.sync="addDialogVisable" width="50%">
        <!-- 表单 -->
        <el-form ref="userFormRef" :rules="userFormRules" :model="addUserInfo" label-width="70px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserInfo.username" ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addUserInfo.password" type="password" ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserInfo.email" ></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="addUserInfo.mobile" ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisable=false">取 消</el-button>
            <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog title="修改用户信息" @close="hiddeneditDialog" :visible.sync="editDialogVisable" width="50%">
        <!-- 表单 -->
        <el-form ref="editFormRel" :rules="editFormRules" :model="editUserInfo" label-width="70px">
            <el-form-item label="用户名">
                <el-input v-model="editUserInfo.username" ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editUserInfo.email" ></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="editUserInfo.mobile" ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisable=false">取 消</el-button>
            <el-button type="primary" @click="editUser()">确 定</el-button>
        </span>
    </el-dialog>

     <!-- 分配角色对话框 -->
    <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        center
        @close="setRoleDialogClosed"
        width="50%">
        <h5>当前用户:{{roleUser.username}}</h5>
        <h5>当前角色:{{roleUser.role_name}}</h5>
        <h5>分配角色:
            <el-select v-model="selectRoleId" placeholder="请选择" >
                <el-option
                v-for="item in rolelist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
                </el-option>
            </el-select>
        </h5>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
    </el-dialog>

</div>
</template>
<script>
export default {
    name:'users',
    data(){
         // 自定义验证规则,邮箱和手机
        const checkEmail=(rule,value,cb)=>{
            const regemail=/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
            if(regemail.test(value)){
                return cb()
            }
            cb(new Error('邮箱格式不正确'))
        }
        const checkMobile=(rule,value,cb)=>{
            const regMobile=/^1(3|4|5|6|7|8|9)\d{9}$/
            if(regMobile.test(value)){
                return cb()
            }
            cb(new Error('请输入正确的手机号'))
        }
        return {
            queryinfo:{
                query:'',
                pagenum:1,//当前页数
                pagesize:3//当前页显示的条数
            },
            userlist:[],
            total:0,
            addUserInfo:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addDialogVisable:false,
            // 编辑表单数据属性
            editUserInfo:{
                id:0,
                username:'',
                email:'',
                mobile:''
            },
            editDialogVisable:false,
            userFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }

                ]
            },
             editFormRules:{
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }

                ]
            },
            setRoleDialogVisible:false,
            roleUser:{},
            rolelist:[],
            selectRoleId:''
        }
    },
    created(){
        this.getUsers()
    },
    methods:{
        async getUsers(){
            const{data:res}=await this.$http.get('users',{params:this.queryinfo})
            if(res.meta.status!=200){
                return this.$message.error('获取用户数据失败')
            }else{
                this.userlist=res.data.users
                this.total=res.data.total
            }
        },
        async changeState(user){
            const{data:res}=await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
            if(res.meta.status!=200){
                return this.$message.error('更新用户状态失败')
                user.mg_state=!user.mg_state
            }
            this.$message.success('更新状态成功')
        },
        // pagesize改事件
        handleSizeChange(newsize){
            this.queryinfo.pagesize=newsize
            this.getUsers()
        },
        // 页码值发生改变的事件
        handleCurrentChange(newpage){
            this.queryinfo.pagenum=newpage
            this.getUsers()
        },
        // 对话框显示
        showAddDialog(){
            this.addDialogVisable=true
        },
         showeditDialog(row){
            this.editDialogVisable=true
            this.editUserInfo=row
        },
        // 隐藏对话框
        hiddenAddDialog(){
            this.addDialogVisable=false
            this.$refs.userFormRef.resetFields()
        },
        hiddeneditDialog(){

        },
        
        addUser(){
            this.$refs.userFormRef.validate(async valid=>{
                if(!valid) return
                const{data:res}=await this.$http.post('users',this.addUserInfo)
                if(res.meta.status!=201){
                return this.$message.error('添加用户失败')
                }
                this.$message.success('添加用户成功')
                this.addDialogVisable=false
                this.getUsers()
            })
        },
        editUser(){
            this.$refs.editFormRel.validate(async valid=>{
                if(!valid)return
                const{data:res}=await this.$http.put(`users/${this.editUserInfo.id}`,{email:this.editUserInfo.email,mobile:this.editUserInfo.mobile})
                if(res.meta.status!=200){
                    return this.$message.error('编辑用户失败')
                }
                this.$message.success('编辑用户成功')
                this.editDialogVisable=false
                this.getUsers()
            })
            
        },
        async deleteUser(id){
            const result=await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(result=='confirm'){
                const{data:res}=await this.$http.delete(`users/${id}`)
                if(res.meta.status==200){
                    this.$message({type: 'success',message: '删除成功!'})
                    this.getUsers()
                }else{
                    return this.$message.error(res.meta.msg)
                }       
            }
        },
        async setUser(user){
            this.roleUser=user
            const{data:res}=await this.$http.get(`roles`)
            if(res.meta.status!=200){
                return $message.error('获取角色列表失败')
            }
            this.rolelist=res.data
            this.setRoleDialogVisible=true

        },
        setRoleDialogClosed(){
            this.roleUser={}
            this.selectRoleId=''
        },
        async saveRole(){
            if(!this.selectRoleId){
                return this.$message.error('请选择角色列表')
            }
            const{data:res}=await this.$http.put(`users/${this.roleUser.id}/role`,{rid:this.selectRoleId})
            if(res.meta.status!=200){
                return this.$message.error(res.meta.msg)
            }
            this.$message.success('分配角色成功')
            this.getUsers()
            this.setRoleDialogVisible=false
        }
    }
}
</script>
<style lang="less" scoped>
    
</style>